package com.ltmall.api.dao.impl;

import com.ltmall.api.bean.*;
import com.ltmall.api.dao.IAccountDAO;
import com.ltmall.api.util.EmojiFilter;
import com.ltmall.api.util.PageUtil;
import org.apache.http.util.TextUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate5.HibernateCallback;

import java.sql.SQLException;
import java.util.List;

import static com.ltmall.api.util.HibernateUtil.getSession;

public class AccountDAO extends BaseEntityDAO<ClientAccount> implements
		IAccountDAO {

    @Override
	@SuppressWarnings("rawtypes")
	public boolean isPhoneUsed(String phone) {
		List list = this.getHibernateTemplate().find(
				"from ClientAccount ca where ca.phone =?",
				new Object[] { phone });
		if (list.size() > 0) {
			return true;

		}
		return false;
	}

	public int isHaveAccount(final String openid){
		final String SQL;
		if(!TextUtils.isEmpty(openid)){
			SQL = "SELECT PLATFORMS.USER_ID"
					+ " from TH_CLIENT_PLATFORMS PLATFORMS"
					+ " where PLATFORMS.OPEN_ID =?";
		}else {
			return -1;
		}
		List<Integer> list = this.getHibernateTemplate().execute(
				new HibernateCallback<List>() {
					public List doInHibernate(Session session)
							throws HibernateException, SQLException {
						Query query = session.createSQLQuery(SQL);
						query.setParameter(0, openid);
						return query.list();
					}
				});
		if (list.isEmpty()) {
			return -1;
		} else {
			return (int)list.get(0);
		}
		
	}

	@Override
	public void addClientConfig(ClientConfig config) {
		config.setOpTime(System.currentTimeMillis());
		try {
			getHibernateTemplate().persist(config);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void addClientInfo(ClientInfo info) {
		info.setOpTime(System.currentTimeMillis());
		try {
		  String name=  EmojiFilter.filterEmoji(info.getName());
		  info.setName(name);
			getHibernateTemplate().persist(info);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

    @Override
	@SuppressWarnings("rawtypes")
	public boolean phoneLogin(String phone, String pass) {
		List list = this.getHibernateTemplate().find(
				"from ClientAccount ca where ca.phone =? and ca.pass = ?",
				new Object[] { phone, pass });
		if (list.size() > 0) {
			return true;

		}
		return false;
	}

    @Override
	public boolean updateToken(int userID, String token) {
		String hql = "update ClientConfig config set config.userToken = ? where config.userID = ?";
		try {
			Session session = getSession();
			Query query = session.createQuery(hql);
			query.setParameter(0, token);
			query.setParameter(1, userID);
			int number = query.executeUpdate();
			if (number == 1) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

    @Override
	@SuppressWarnings("rawtypes")
	public ClientConfig getConfig(int userID) {
		List list = this.getHibernateTemplate().find(
				"from ClientConfig cc where cc.userID =?",
				new Object[] { userID });
		if (list.size() > 0) {
			return (ClientConfig) list.get(0);
		}
		return null;
	}

    @Override
	@SuppressWarnings("rawtypes")
	public ClientAccount getAccount(String phone, int userID) {
		String hql;
		Object param;
		if (phone == null) {
			hql = "from ClientAccount ca where ca.userID =?";
			param = userID;
		} else {
			hql = "from ClientAccount ca where ca.phone =?";
			param = phone;
		}

		List list = this.getHibernateTemplate().find(hql,
				new Object[] { param });
		if (list.size() > 0) {
			return (ClientAccount) list.get(0);
		}
		return null;
	}

    @Override
	public boolean updateInfo(int userID, String name, int sex) {
		// TODO Auto-generated method stub
		String hql;
		Object param;
		if (name == null) {
			hql = "update ClientInfo info set info.sex = ?"
					+ "where info.userID = ?";
			param = sex;
		} else {
			hql = "update ClientInfo info set info.name = ?"
					+ "where info.userID = ?";
			param = name;
		}

		try {
			Session session = getSession();
			Query query = session.createQuery(hql);
			query.setParameter(0, param);
			query.setParameter(1, userID);
			int number = query.executeUpdate();
			if (number == 1) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

    @Override
	public boolean updateLevel(int userId, int levelId) {
		String hql = "update ClientInfo info set info.levelId = ? where info.userID = ?";
		try {
			Session session = getSession();
			Query query = session.createQuery(hql);
			query.setParameter(0, levelId);
			query.setParameter(1, userId);
			int number = query.executeUpdate();
			if (number == 1) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

    @Override
	public boolean validate(int userID, String userToken) {
		@SuppressWarnings("rawtypes")
		List list = this.getHibernateTemplate().find(
				"from ClientConfig cc where cc.userID =? and cc.userToken = ?",
				new Object[] { userID, userToken });
		if (list.size() > 0) {
			return true;

		}
		return false;
	}

    @Override
	@SuppressWarnings("rawtypes")
	public ClientInfo getInfo(int userID) {
		List list = this.getHibernateTemplate().find(
				"from ClientInfo info where info.userID =?",
				new Object[] { userID });
		if (list.size() > 0) {
			return (ClientInfo) list.get(0);
		}
		return null;
	}

    @Override
	public boolean updatePhoto(int userID, String photo) {
		String hql = "update ClientInfo info set info.photo = ?"
				+ "where info.userID = ?";
		try {
			Session session = getSession();
			Query query = session.createQuery(hql);
			query.setParameter(0, photo);
			query.setParameter(1, userID);
			int number = query.executeUpdate();
			if (number == 1) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

    @Override
	public boolean addDelevery(DeliveryAddr addr) {
		addr.setOpTime(System.currentTimeMillis());
		try {
			getHibernateTemplate().persist(addr);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean updateDelevery(int addrID, int userID, String name,
			String phone, String address, String province, String city,
			String county, int isDefault) {
		// TODO Auto-generated method stub
		String hql = "update DeliveryAddr addr set addr.name = ?,addr.phone = ?,addr.address = ?,addr.isDefault = ?,addr.province=?,addr.city=?,addr.county=?"
				+ "where addr.addrID = ?";
		try {
			Session session = getSession();
			Query query = session.createQuery(hql);
			query.setParameter(0, name);
			query.setParameter(1, phone);
			query.setParameter(2, address);
			query.setParameter(3, isDefault);
			query.setParameter(4, province);
			query.setParameter(5, city);
			query.setParameter(6, county);
			query.setParameter(7, addrID);

			int number = query.executeUpdate();
			if (number == 1) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public void updateOtherDelevery(int userID, int addrID, int isDefault) {
		String hql = "update DeliveryAddr addr set addr.isDefault = ?"
				+ "where addr.userID = ? and addr.addrID!=?";
		try {
			Session session = getSession();
			Query query = session.createQuery(hql);
			query.setParameter(0, isDefault);
			query.setParameter(1, userID);
			query.setParameter(2, addrID);
			query.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean deleDelivery(int addrID) {
		String hql = "delete DeliveryAddr addr where addr.addrID = ?";
		try {
			Session session = getSession();
			Query query = session.createQuery(hql);
			query.setParameter(0, addrID);
			int opNumber = query.executeUpdate();
			if (opNumber == 1)
				return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<DeliveryAddr> getDelivery(final int userID, int number) {
		String SQL = "from DeliveryAddr addr where addr.userID = ? ";
        // 获取默认的地址
		if (number == 1) {
			SQL = "from DeliveryAddr addr where addr.userID = ? and addr.isDefault =1";
		}
		final String HQL = SQL;
		@SuppressWarnings("rawtypes")
		List<DeliveryAddr> list = this.getHibernateTemplate().execute(
				new HibernateCallback<List>() {
					public List doInHibernate(Session session)
							throws HibernateException, SQLException {
						Query query = session.createQuery(HQL);
						query.setParameter(0, userID);
						return query.list();
					}
				});
		return list;
	}

	@Override
	public boolean updatePass(int userID, String pass) {
		String hql = "update ClientAccount account set account.pass = ?"
				+ "where account.userID = ?";
		try {
			Session session = getSession();
			Query query = session.createQuery(hql);
			query.setParameter(0, pass);
			query.setParameter(1, userID);
			int opNumber = query.executeUpdate();
			if (opNumber == 1) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean addBussinessInfo(BussinessInfo info) {
		info.setOpTime(System.currentTimeMillis());
		try {
			getHibernateTemplate().persist(info);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public void addBussinessAccount(BussinessAccount bAccount) {
		bAccount.setOpTime(System.currentTimeMillis());
		try {
			getHibernateTemplate().persist(bAccount);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	@SuppressWarnings("rawtypes")
	public DeliveryAddr getAddr(int addrID) {
		List list = this.getHibernateTemplate().find(
				"from DeliveryAddr da where da.addrID =?",
				new Object[] { addrID });
		if (list.size() > 0) {
			return (DeliveryAddr) list.get(0);
		}
		return null;
	}

	@Override
	public boolean addCollection(Collection collection) {
		collection.setOpTime(System.currentTimeMillis());
		try {
			getHibernateTemplate().persist(collection);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean isCollectionExist(Collection collection) {
		String hql = "from Collection co where co.goodsID =? and co.userID = ?";
		Object[] obj = new Object[] { collection.getGoodsID(), collection.getUserID() };
		 
		List<?> list = this.getHibernateTemplate().find(hql, obj);
		if (list.size() > 0) {
			return true;
		}
		return false;
	
	}

	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List<?> collectionList(final int userID,final PageUtil page) {
		String headHQL, endHQL;
		headHQL = "SELECT COLLECTION.COLLECTION_ID,GOODS.GOODS_ID,GOODS.GOODS_NAME,GOODS.GOODS_PICTURE,GOODS.GOODS_PRICE,GOODS.GOODS_TITLE";
		endHQL = " from FLAVOR_GOODS GOODS left join FLAVOR_COLLECTION COLLECTION on GOODS.GOODS_ID = COLLECTION.GOODS_ID "
				+ " where COLLECTION.USER_ID =? ";
		final String SQL = headHQL + endHQL;
		List<Integer> list = this.getHibernateTemplate().execute(
				new HibernateCallback<List>() {
					public List doInHibernate(Session session)
							throws HibernateException, SQLException {
						Query query = session.createSQLQuery(SQL);
						query.setParameter(0, userID);
						// 分页
						query.setFirstResult((page.getCur_page() - 1)* page.getNumPerPage()).setMaxResults(page.getNumPerPage());
						return query.list();
					}
				});
		return list;
	}

	@Override
	public boolean editHome(int userID, String province, String city,
			String county) {
		String hql = "update ClientInfo info set info.province = ?,info.city = ?,info.county = ?"
				+ "where info.userID = ?";
		try {
			Session session = getSession();
			Query query = session.createQuery(hql);
			query.setParameter(0, province);
			query.setParameter(1, city);
			query.setParameter(2, county);
			query.setParameter(3, userID);
			int number = query.executeUpdate();
			if (number == 1) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean editDirectSupplyId(int userID, String directSupplyId) {
        String hql = "update ClientInfo info set info.linkedDirectSupplyId = ?"
                + "where info.userID = ?";
        try {
            Session session = getSession();
            Query query = session.createQuery(hql);
            query.setParameter(0, new Integer(directSupplyId));
            query.setParameter(1, userID);
            int number = query.executeUpdate();
            if (number == 1) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
	public boolean cancelCollection(int goodsID,int userID) {
		String hql = "delete Collection coll where coll.goodsID = ? and coll.userID = ?";
		try {
			Session session = getSession();
			Query query = session.createQuery(hql);
			query.setParameter(0,goodsID);
			query.setParameter(1, userID);
			int opNumber = query.executeUpdate();
			System.out.println("========"+opNumber+"======");
			if (opNumber == 1) {
                return true;
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean addFeedback(Feedback feedback) {
		feedback.setOpTime(System.currentTimeMillis());
		try {
			getHibernateTemplate().persist(feedback);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public ThClientPlatforms checkUserExistByOpenID(String opendID) {
		String hql = "from ThClientPlatforms cp where cp.openId = ?";
		List list = this.getHibernateTemplate().find(hql,new Object[] { opendID });
		if (list.size() > 0) {
			return (ThClientPlatforms) list.get(0);
		}
		return null;
	}

	@Override
	public void addClientPlatform(ThClientPlatforms platform) {
		try {
			getHibernateTemplate().persist(platform);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public ThUserLevels userLevelGet(int levelId) {
		String hql = "from ThUserLevels ul where ul.id = ?";
		List list = this.getHibernateTemplate().find(hql,new Object[] { levelId });
		if (list.size() > 0) {
			return (ThUserLevels) list.get(0);
		}
		return null;
	}

	@Override
	public ThClientPlatforms getClientPlatformByUserId(int userId) {
		String hql = "from ThClientPlatforms cp where cp.userId = ?";
		List list = this.getHibernateTemplate().find(hql,new Object[] { userId });
		if (list.size() > 0) {
			return (ThClientPlatforms) list.get(0);
		}
		return null;
	}

	@Override
	public ThClientPlatforms getClientPlatformByOpenId(String openId) {
		String hql = "from ThClientPlatforms cp where cp.openId = ?";
		List list = this.getHibernateTemplate().find(hql,new Object[] { openId });
		if (list.size() > 0) {
			return (ThClientPlatforms) list.get(0);
		}
		return null;
	}

	@Override
	public boolean saveClientAccount(ClientAccount clientAccount) {
		Session session = getSession();
		try {
			session.saveOrUpdate(clientAccount);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			//releaseSession(session);
		}
	}
}
